import { ref, watch } from 'vue';
import { smartSentry } from '/@/lib/smart-sentry';
import { message, Modal } from 'ant-design-vue';
import { SmartLoading } from '/@/components/framework/smart-loading';
import * as dictList from "/@/constants/common-const.js"

const queryFormState = {
  pageNum: 1,
  pageSize: 10,
};

export const getDictLabel = (val, dict, props = { label: "label", value: "value" }) => {
  const row = dict.find(m => m[props.value] == val) || {};
  return row[props.label];
}

export function PageMixin() {
  // 查询表单form
  let queryForm = ref({ ...queryFormState });
  // 总数
  const total = ref(0);
  // 表格加载loading
  const tableLoading = ref(false);
  // 表格数据
  const tableData = ref([]);
  // 选择表格行
  const selectedRowKeyList = ref([]);
  // 重置查询条件
  function resetQueryForm(defalutData = {}) {
    let pageSize = queryForm.value.pageSize;
    queryForm.value = Object.assign({}, queryFormState, defalutData)
    queryForm.value.pageSize = pageSize;
    return queryForm.value
  }
  // 表格请求
  async function queryTableData(api, params = queryForm.value) {
    tableLoading.value = true;
    try {
      // 替换分页参数
      const { pageNum, pageSize, ...rest } = params;
      // 发出请求
      let queryResult = await api({
        current: pageNum ?? params.current,
        size: pageSize ?? params.size,
        ...rest
      });
      tableData.value = queryResult.data.records;
      total.value = queryResult.data.total;
    } catch (e) {
      smartSentry.captureError(e);
    } finally {
      tableLoading.value = false;
    }
  }
  // 确认删除
  function deleteFn(data, api, keyId) {
    return new Promise((r) => {
      Modal.confirm({
        title: '提示',
        content: '确定要删除选吗?',
        okText: '删除',
        okType: 'danger',
        onOk() {
          SmartLoading.show();
          try {
            api(data[keyId]).then(() => {
              message.success('删除成功');
              r()
              // queryData();
            })
          } catch (e) {
            smartSentry.captureError(e);
          } finally {
            SmartLoading.hide();
          }
        },
        cancelText: '取消',
        onCancel() { },
      });
    })
  }
  function batchDeleteFn(api) {
    return new Promise((r) => {
      if (selectedRowKeyList.value.length === 0) {
        message.warning('请先选择删除项');
        r(false)
      } else {
        Modal.confirm({
          title: '提示',
          content: '确定要批量删除这些数据吗?',
          okText: '删除',
          okType: 'danger',
          onOk() {
            try {
              SmartLoading.show();
              api(selectedRowKeyList.value).then(() => {
                message.success('删除成功');
                selectedRowKeyList.value = [];
                r(true)
              });
            } catch (e) {
              smartSentry.captureError(e);
              r(false)
            } finally {
              SmartLoading.hide();
            }
          },
          cancelText: '取消',
          onCancel() { },
        });
      }
    })
  }

  function watchTotal(query, fn) {
    watch(
      () => total.value,
      (newValue) => {
        // 判断总数和页码能不能对上
        if (query.value.pageNum !== 1) {
          if ((query.value.pageNum - 1) * query.value.pageSize >= newValue) {
            query.value.pageNum -= 1;
            fn();
          }
        }
      }
    );
  }
  function deepClone(obj) {
    return JSON.parse(JSON.stringify(obj));
  }

  // ✅ 通用重置函数
  function resetForm(target, defaults) {
    // 清除 target 的所有键
    Object.keys(target).forEach((key) => {
      delete target[key];
    });

    // 添加 defaults 中的键，值为深拷贝后的内容
    Object.keys(defaults).forEach((key) => {
      const val = defaults[key];
      target[key] = val === undefined ? undefined : deepClone(val);
    });
  }

  return {
    queryForm,
    total,
    tableLoading,
    tableData,
    selectedRowKeyList,
    resetQueryForm,
    queryTableData,
    deleteFn,
    batchDeleteFn,
    dictList,
    queryFormState,
    watchTotal,
    resetForm,
  };
}